$(document).ready(function() {

    function validatePasswords(pw1, pw2) {
        if (pw1 == pw2) {
            return true;
        } else {
            $('#create_user_msg').html('<b><font color="red">Lösenorden överensstämmer inte</font></b>').hide().delay(200).fadeIn();
            return false;
        }
    }

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'agendaDay,month'
        },
        
        firstDay: 1,
        axisFormat: 'HH:mm',
        allDaySlot: false,

        defaultView: 'agendaDay',
    
        editable: false,
        
        eventSources: [
            {
                url: 'events.php',
                type: 'GET',
                error: function() {
                    alert('Sessionen har utgått... ');
                    window.location = 'kill_session.php';
                } 
            }
        ],

        dayClick: function(date, allDay, jsEvent, view) {
            if (view.name == 'month' && isUser == 0) { 
                $('#calendar').fullCalendar('changeView', 'agendaDay');
                $('#calendar').fullCalendar('gotoDate', date.getFullYear(), date.getMonth(), date.getDate());
            }
        },
        
        eventClick: function(calEvent, jsEvent, view) {
            $('#event_id').text(calEvent.eid);
            $('#event_desc').text(calEvent.title);
            $('#event_start').text(calEvent.start.toLocaleString());
            $('#event_stop').text(calEvent.end != null ? calEvent.end.toLocaleString() : 'ERROR WTF');
            $('#event_etype').text(calEvent.etype);
            $('#event_name').text(calEvent.name);
            $('#event_pubshare').text(calEvent.pubshare ? 'Ja' : 'Nej');
            $('#event_details_msg').html('');

            $('#event_details_window').dialog("open");
        },

        selectable: isUser != 0,
        
        select: function(start, end, allDay, jsEvent, view) {
            if (view.name == 'agendaDay') {
                $('#add_event_desc').val('');
                $('#add_event_start').val(start.getTime());
                $('#add_event_start_human').html(start.toLocaleString());
                $('#add_event_end').val(end.getTime());
                $('#add_event_end_human').html(end.toLocaleString());
                $('input[id^="etype"]').attr('checked', false);
                $('#etype-custom').hide();;
                $('#add_event_msg').html('');
                $('#add_event_window').dialog('open');
            } else {
                // Zoom in 
                $('#calendar').fullCalendar('changeView', 'agendaDay');
                $('#calendar').fullCalendar('gotoDate', start.getFullYear(), start.getMonth(), start.getDate());
            }
        }
    });
    
    $('#login_window').dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        height: 320,
        buttons: {
            "Logga in": function() {
                $('#login_form').submit();
            },
            Avbryt: function() {$(this).dialog("close");}
        }
    });

    
    $('#create_user_window').dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        height: 500,
        buttons: {
            "Skapa användare": function() {
                // check the passwords
                var b = validatePasswords($('#create_user_form input[name=password2]').val(), $('#create_user_form input[name=password]').val());
                if (!b) {
                    return false;
                }

                var a = $('#create_user_form').serialize();
                $.post('create_user.php', a, function(data) {
                    var out = eval('(' + data + ')');
                    if (out.error) {
                            $('#create_user_msg').html('<b><font color="red">Error: ' + out.error + '</font></b>').hide().delay(200).fadeIn();
                        } else {
                            $('#create_user_msg').html('<b><font color="green">Din användare har skapats. Du kan nu logga in med den. Kopplar om. </font></b><img src="img/dots.gif">').fadeIn("slow");
                            setTimeout(function() {window.location = '/';}, 2000);
                        } 
                });
            },
            Avbryt: function() {$(this).dialog("close");}
        }
    });

    $('#change_password_window').dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        height: 400,
        create: function(event, ui) {
            var buttons =  {};
            if (isUser != 0) {
                buttons.Ändra = function() {
                    var a = $('#change_password_form').serialize();
                    $('#event_details_msg').html('<img src="img/dots.gif">').hide().delay(200).fadeIn();
                    $.post('change_password.php', a, function(data) {
                    var out = eval('(' + data + ')');
                    if (out.error) {
                            $('#change_password_msg').html('<b><font color="red">Fel: ' + out.error + '</font></b>').hide().delay(200).fadeIn();
                        } else {
                            $('#change_password_msg').html('<b><font color="green">Lösenordet är bytt. </font></b><img src="img/dots.gif">').fadeIn("slow");
                            setTimeout(function() {window.location = '/';}, 2000);
                        }
                    });
                };
            }
            buttons.Avbryt = function() {$(this).dialog("close");}
            $(this).dialog( "option", "buttons", buttons);
        }
    });
    
    $('#change_picture_window').dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        height: 450,
        buttons: {
            "Ladda up": function() {
                $('#change_picture_form').submit();
            },
            Avbryt: function() {$(this).dialog("close");}
        }
    });

    $('#event_details_window').dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        height: 300,
        create: function(event, ui) {
            var buttons =  {};
            if (isUser != 0) {
                buttons.Radera = function() {
                    var a = "eid=" + $('#event_id').text();
                    $('#event_details_msg').html('<img src="img/dots.gif">').hide().delay(200).fadeIn();
                    $.post('delete_event.php', a, function(data) {
                        var out = eval('(' + data + ')');
                        if (out.error) {
                                $('#event_details_msg').html('<b><font color="red">Fel: ' + out.error + '</font></b>').hide().delay(200).fadeIn();
                            } else {
                                $('#calendar').fullCalendar('refetchEvents');
                                $('#event_details_msg').html('<b><font color="green">Händelsen borttagen. </font></b><img src="img/dots.gif">').hide().delay(200).fadeIn("slow");
                                setTimeout(function() {window.location = '/';}, 2000);
                            } 
                    });
                };
            }
            buttons.Avbryt = function() {$(this).dialog("close");}
            $(this).dialog( "option", "buttons", buttons);
        }
    });
    

    $('#add_event_window').dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        height: 600,
        open: function() {
            $.get('eventtypes.php', function(data) {
                var out = eval('(' + data + ')');
                if (out.error) {
                    $('#add_event_msg').html('<b><font color="red">Fel: ' + out.error + '</font></b>').hide().delay(200).fadeIn();
                } else {
                    var str = "";
                    for (i = 0; i < out.length; i++) {
                        str += '<input id="etype-"' + i + '" type="radio" name="etype" value="' + out[i].et_desc + '">';
                        str += '<label for="etype-"' + i + '">' + out[i].et_desc + '</label><br>';
                    }
                    str += '<input id="etype-radio-custom" name="etype" type="radio" value="custom"><label for="etype-radio-custom">Egen</label>';
                    $('#etype-radio').html(str);

                    $('input[id^=etype-]').change(function() {
                        $('#etype-custom').delay(200).fadeOut();
                    });

                    $('#etype-radio-custom').change(function() {
                        $('#etype-custom').hide().delay(200).fadeIn();
                    });
                    
                }
            });
        },
        buttons: {
            Skapa: function() {
                var a = $('#add_event_form').serialize();
                $.post('add_event.php', a, function(data) {
                    var out = eval('(' + data + ')');
                    if (out.error) {
                            $('#add_event_msg').html('<b><font color="red">Fel: ' + out.error + '</font></b>').hide().delay(200).fadeIn();
                        } else {
                            $('#calendar').fullCalendar('refetchEvents');
                            $('#add_event_msg').html('<b><font color="green">Händelsen skapad. </font></b><img src="img/dots.gif">').hide().delay(200).fadeIn("slow");
                            setTimeout(function() {window.location = '/';}, 2000);
                        } 
                });
            },
            Avbryt: function() {$(this).dialog("close");}
        }
    });
});
